<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/3/17
  Time: 16:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>地区三级联动[struts2-json]</title>
    <script type="text/javascript" src="../js/ajax.js"></script>
</head>
<body>
<%--三级 并列--%>
<select id="provinceID" style="margin-left: 10%">
    <option >选择省份</option>
    <option>湖北</option>
    <option>湖南</option>
    <option>广东</option>
</select>
&nbsp;&nbsp;&nbsp;&nbsp;
<select id="cityID">
    <option >选择城市</option>
</select>
&nbsp;&nbsp;&nbsp;&nbsp;
<select id="areaID">
    <option >选择区域</option>
</select>
<script type="text/javascript">
    var province = document.getElementById("provinceID");
    var city = document.getElementById("cityID");
    var county = document.getElementById("areaID");
    province.onchange = function () {
        //清空城市下拉框
        city.options.length=1;
        county.options.length=1;

        //获取选中的名称
        var provinceName = this[this.selectedIndex].innerHTML;
        if("选则省份"!=provinceName){
            console.log(provinceName);
            var ajax = createAJAX();
            var url = "${pageContext.request.contextPath}/json_getcity?time="+new Date().getTime();
            ajax.open("POST",url);
            ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
            ajax.send("bean.province="+provinceName);
            ajax.onreadystatechange=function () {
                if(ajax.readyState==4&&ajax.status==200){
                    // 这里接收的是json
                    var jsonAjax = ajax.responseText;
                    // 然后去解析json
                    // {"bean":{"city":null,"province":"湖南"},"city":"success","cityList":["郴州","张家界","浏阳"]}
                    console.log(jsonAjax);
                    //将Java格式的json文本转换成js格式的json文件
//                    Object {bean: Object, city: "success", cityList: Array[2]}
                    var jsonJs = eval("("+jsonAjax+")");
                    console.log(jsonJs);
                    var array = jsonJs.cityList;//获取city集合
                    for (var i = 0; i < array.length; i++) {
                        var cityName = array[i];
                        var option = document.createElement("option");
                        option.innerHTML = cityName;
                        city.appendChild(option);
                    }
                }
            }
        }
    }
</script>
</body>
</html>
